package token

import (
	"context"
	"fmt"
	"github.com/golang-jwt/jwt"
	"net/http"
	"strings"
)

const Identify = "aiworkc.com"

func GetJwtToken(secretKey string, iat, seconds int64, uid string) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims[Identify] = uid
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

func GetUId(ctx context.Context) string {
	var uid string
	if jsonUid, ok := ctx.Value(Identify).(string); ok {
		uid = jsonUid
	}
	return uid
}

func VerifyJWTTokenFromRequest(secretKey string, r *http.Request) (string, error) {
	// 从请求头中获取 token
	tokenString := r.Header.Get("Authorization")
	if tokenString == "" {
		return "", fmt.Errorf("missing token in authorization header")
	}

	// 如果 token 以 "Bearer " 开头，则去除前缀
	if strings.HasPrefix(tokenString, "Bearer ") {
		tokenString = tokenString[7:]
	}

	// 解析并验证 token
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// 验证签名方法
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(secretKey), nil
	})

	if err != nil {
		return "", err
	}

	// 验证 token 有效性
	if !token.Valid {
		return "", fmt.Errorf("invalid token")
	}

	// 提取 claims
	claims, ok := token.Claims.(jwt.MapClaims)
	if !ok {
		return "", fmt.Errorf("failed to parse claims")
	}

	// 获取用户 ID
	uid, ok := claims[Identify].(string)
	if !ok {
		return "", fmt.Errorf("failed to get user id from token")
	}

	return uid, nil
}
